package org.jeecg.modules.data.controller;

import cn.hutool.core.io.FileUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.data.entity.District;
import org.jeecg.modules.data.entity.TDataReport;
import org.jeecg.modules.data.entity.TDataStatistics;
import org.jeecg.modules.data.service.IDistrictService;
import org.jeecg.modules.data.service.ITDataReportService;
import org.jeecg.modules.data.service.ITDataStatisticsService;
import org.jeecg.modules.data.util.FileUtils;
import org.jeecg.modules.system.service.ISysUserDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description: t_data_statistics
 * @Author: jeecg-boot
 * @Date:   2025-05-20
 * @Version: V1.0
 */
@Api(tags="t_data_statistics")
@RestController
@RequestMapping("/data/tDataStatistics")
@Slf4j
public class TDataStatisticsController extends JeecgController<TDataStatistics, ITDataStatisticsService> {
	@Value(value = "${jeecg.path.template-word-file}")
	private String wordFile;
	@Value(value = "${jeecg.path.template-excel-file}")
	private String excelFile;
	@Value(value = "${jeecg.path.reporturl}")
	private String reporturl;
	@Resource
	private ITDataStatisticsService tDataStatisticsService;
	@Resource
	private ISysUserDistrictService sysDistrictService;
	@Resource
	private ITDataReportService tDataReportService;
	@Resource
	private IDistrictService districtService;

	/**
	 * 列表查询
	 *
	 * @param tDataStatistics
	 * @return
	 */
	@ApiOperation(value="t_data_statistics-列表查询", notes="t_data_statistics-列表查询")
	@GetMapping(value = "/list")
	public Result<List<TDataStatistics>> queryList(TDataStatistics tDataStatistics) {
		String city = null;
		if (StringUtils.isEmpty(tDataStatistics.getType())) {
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			// 根据登录用户获取所属区县
			District district = sysDistrictService.getUserDistrict(user.getId());
			if (district == null) {
				return Result.OK();
			} else if (district.getCantType().equals("1")) {
				tDataStatistics.setType("1");
			} else if (district.getCantType().equals("2")) {
				tDataStatistics.setType("2");
				tDataStatistics.setCantCode(district.getCantCode());
			} else if (district.getCantType().equals("3")) {
				tDataStatistics.setType("3");
				tDataStatistics.setCantCode(district.getCantCode());
			}
		} else if (tDataStatistics.getType().equals("3")) {
			city = districtService.getCityCode(tDataStatistics.getCity()).getShortName(); // 城市
		}
		List<TDataStatistics> list = tDataStatisticsService.selectDataList(tDataStatistics);
		String finalCity = city == null ? "" : city;
		list.forEach(item -> {
			item.setTitle(finalCity + FileUtils.getTitile(item.getName()));
		});
		return Result.OK(list);
	}
	/**
	 * 列表查询
	 *
	 * @param tDataStatistics
	 * @return
	 */
	@ApiOperation(value="t_data_statistics-列表查询", notes="t_data_statistics-列表查询")
	@GetMapping(value = "/childrenList")
	public Result<List<TDataStatistics>> queryChildrenList(TDataStatistics tDataStatistics) {
		String city = null;
		TDataStatistics ts = tDataStatisticsService.getDataInfoById(tDataStatistics.getId());
		tDataStatistics = new TDataStatistics();
		Integer level = 0;
		if (!ts.getType().equals("3")) {
			level = Integer.parseInt(ts.getType())+1;
			tDataStatistics.setCity(ts.getCantCode());
			tDataStatistics.setType(level.toString());

		}
		if (tDataStatistics.getType().equals("3")) {
			city = ts.getCantName();
		}

		tDataStatistics.setInvestigationId(ts.getInvestigationId());
		List<TDataStatistics> list = tDataStatisticsService.selectDataList(tDataStatistics);
		String finalCity = city == null ? "" : city;
		list.forEach(item -> {
			item.setTitle(finalCity + FileUtils.getTitile(item.getName()));
		});
		return Result.OK(list);



	}

	/**
	 *   添加
	 *
	 * @param tDataStatistics
	 * @return
	 */
	@AutoLog(value = "t_data_statistics-添加")
	@ApiOperation(value="t_data_statistics-添加", notes="t_data_statistics-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TDataStatistics tDataStatistics) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		tDataStatistics.setCreateBy(user.getUsername());
		tDataStatistics.setCreateTime(new Date());
		tDataStatisticsService.save(tDataStatistics);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tDataStatistics
	 * @return
	 */
	@AutoLog(value = "t_data_statistics-编辑")
	@ApiOperation(value="t_data_statistics-编辑", notes="t_data_statistics-编辑")
	@PostMapping(value = "/edit")
	public Result<String> edit(@RequestBody TDataStatistics tDataStatistics) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		tDataStatistics.setUpdateBy(user.getUsername());
		tDataStatistics.setUpdateTime(new Date());
		tDataStatisticsService.updateById(tDataStatistics);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param tDataStatistics
	 * @return
	 */
	@AutoLog(value = "t_data_statistics-通过id删除")
	@ApiOperation(value="t_data_statistics-通过id删除", notes="t_data_statistics-通过id删除")
	@PostMapping(value = "/delete")
	public Result<String> delete(@RequestBody TDataStatistics tDataStatistics) {
		tDataStatisticsService.removeById(tDataStatistics.getId());
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param tDataStatistics
	 * @return
	 */
	@AutoLog(value = "t_data_statistics-批量删除")
	@ApiOperation(value="t_data_statistics-批量删除", notes="t_data_statistics-批量删除")
	@PostMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestBody TDataStatistics tDataStatistics) {
		String ids = tDataStatistics.getId();
		this.tDataStatisticsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "t_data_statistics-通过id查询")
	@ApiOperation(value="t_data_statistics-通过id查询", notes="t_data_statistics-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TDataStatistics> queryById(@RequestParam(name="id",required=true) String id) {
		TDataStatistics tDataStatistics = tDataStatisticsService.getById(id);
		if(tDataStatistics==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tDataStatistics);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tDataStatistics
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TDataStatistics tDataStatistics) {
        return super.exportXls(request, tDataStatistics, TDataStatistics.class, "t_data_statistics");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TDataStatistics.class);
    }

    /**
    * 县级——导出word
    * @param request
    * @return
    */
    @RequestMapping(value = "/exportAreaWord")
    public void exportAreaWord(HttpServletRequest request, HttpServletResponse response, TDataStatistics tDataStatistics) {
		TDataStatistics statistics = tDataStatisticsService.getDataInfoById(tDataStatistics.getId());
		InputStream ins = null;
		try {
			// Step.1、判断模板文件是否存在
			File templateFile = new File(wordFile);
			if (!templateFile.exists()){
				throw new IOException("模板文件不存在:" + wordFile);
			}
			//获取Word模板，模板存放路径
			ins = new FileInputStream(templateFile);
			//注册xdocreport实例并加载FreeMarker模板引擎
			IXDocReport docReport = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
			//创建xdocreport上下文对象，用于存放具体数据
			IContext context = docReport.createContext();
			//创建要替换的文本变量
			TDataReport tDataReport = new TDataReport();
			tDataReport.setInvestigationId(statistics.getInvestigationId());
			tDataReport.setCantCode(statistics.getCantCode());
			List<TDataReport> report = tDataReportService.selectAreaList(tDataReport);
			context.put("report", report);

			// 非列表字段
			context.put("title", FileUtils.getTitile(statistics.getName()));
			context.put("realname", statistics.getRealname());
			context.put("phone", statistics.getPhone());
			context.put("townCount", statistics.getTownCount());
			context.put("samplingPointCount", statistics.getSamplingPointCount());
			context.put("averageLossRate", statistics.getAverageLossRate());
			//创建字段元数据
			FieldsMetadata fm = docReport.createFieldsMetadata();
			//Word模板中的表格数据对应的集合类型
			fm.load("report", TDataReport.class, true);
			//输出到本地目录
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/msword");
			docReport.process(context, response.getOutputStream());
		} catch (Exception e) {
			System.out.println("生成word发生异常"+e);
		}finally {
			try {
				if (ins != null){
					ins.close();
				}
			} catch (IOException e) {
				System.out.println("文件流关闭失败"+e);
			}
		}
    }

	/**
	 * 导出压缩文件
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("exportZipFile")
	public void exportZipFile(HttpServletResponse response, TDataStatistics tDataStatistics) throws IOException {
		TDataStatistics statistics = tDataStatisticsService.getDataInfoById(tDataStatistics.getId());
//		TDataStatistics statistics = tDataStatisticsService.getDataInfoById("e9ddb9228d1b4d459608f298c4fc4060");
		// 生成导出文件
		List<Map<String, String>> wordFiles = tDataStatisticsService.generateReportFiles(statistics, wordFile, excelFile, reporturl);
		String filename = statistics.getCantName() + ".zip";
		response.setContentType("application/OCTET-STREAM;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename="
				+ new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

		try (ServletOutputStream outputStream = response.getOutputStream();
			 ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
			for (Map<String, String> wordFile : wordFiles) {
				zipOutputStream.putNextEntry(new ZipEntry(wordFile.get("fileName")));
				byte[] docFile = FileUtil.readBytes(wordFile.get("filePath"));
				zipOutputStream.write(docFile);
				zipOutputStream.flush();
				zipOutputStream.closeEntry();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
